// ai 不要修改这个文件, 这个文件是参考代码
/*
 * @Author: AI Assistant
 * @Date: 2024-05-07 15:30:00
 * @Last Modified by: AI Assistant
 * @Last Modified time: 2024-05-07 15:30:00
 */

// 后台管理系统页面模板的标签子组件Store文件

import { makeAutoObservable, observable, action, flow } from 'mobx';

/**
 * 标签项接口定义
 * 用于存储和管理标签数据
 */
export interface LableItem {
  /**
   * 标签唯一ID
   */
  id: string;
  
  /**
   * 标签文本内容
   */
  text: string;
  
  /**
   * 标签类型
   */
  type: 'default' | 'primary' | 'success' | 'warning' | 'error' | 'info' | 'danger';
  
  /**
   * 标签大小
   */
  size?: 'small' | 'medium' | 'large';
  
  /**
   * 是否可关闭
   */
  closable: boolean;
  
  /**
   * 是否禁用
   */
  disabled: boolean;
  
  /**
   * 标签创建时间戳
   */
  createdAt: number;
  
  /**
   * 标签的额外数据
   */
  extra?: Record<string, any>;
}

/**
 * LableStore类
 * 负责管理标签组件的状态和业务逻辑
 * 提供添加、删除、更新标签等功能
 */
class LableStore {
  /**
   * 标签列表
   */
  lables: LableItem[] = observable([] as LableItem[]);
  
  /**
   * 当前选中的标签ID
   */
  selectedLableId: string | null = null;
  
  /**
   * 标签加载状态
   */
  loading: boolean = false;
  
  /**
   * 标签错误信息
   */
  error: string | null = null;
  
  /**
   * 标签总数
   */
  totalCount: number = 0;
  
  /**
   * 构造函数
   * 初始化Store，设置响应式属性和操作
   */
  constructor() {
    makeAutoObservable(this, {
      lables: observable,
      selectedLableId: observable,
      loading: observable,
      error: observable,
      totalCount: observable,
      addLable: action,
      removeLable: action,
      updateLable: action,
      clearLables: action,
      setSelectedLable: action,
      fetchLables: flow,
    });
  }
  
  /**
   * 添加标签
   * @param lable 标签数据
   */
  addLable = (lable: Omit<LableItem, 'id' | 'createdAt'>): void => {
    const newLable: LableItem = {
      ...lable,
      id: `lable_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      createdAt: Date.now(),
    };
    
    this.lables.push(newLable);
    this.totalCount = this.lables.length;
  };
  
  /**
   * 移除标签
   * @param id 标签ID
   */
  removeLable = (id: string): void => {
    const index = this.lables.findIndex(item => item.id === id);
    if (index !== -1) {
      this.lables.splice(index, 1);
      this.totalCount = this.lables.length;
      
      // 如果移除的是当前选中的标签，则清除选中状态
      if (this.selectedLableId === id) {
        this.selectedLableId = null;
      }
    }
  };
  
  /**
   * 更新标签
   * @param id 标签ID
   * @param updates 更新内容
   */
  updateLable = (id: string, updates: Partial<LableItem>): void => {
    const lable = this.lables.find(item => item.id === id);
    if (lable) {
      Object.assign(lable, updates);
    }
  };
  
  /**
   * 清空标签列表
   */
  clearLables = (): void => {
    // 使用直接赋值的方式清空数组
    this.lables.length = 0;
    this.totalCount = 0;
    this.selectedLableId = null;
  };
  
  /**
   * 设置选中的标签
   * @param id 标签ID，为null时清除选中状态
   */
  setSelectedLable = (id: string | null): void => {
    this.selectedLableId = id;
  };
  
  /**
   * 根据类型筛选标签
   * @param type 标签类型
   * @returns 符合条件的标签列表
   */
  getLablesByType = (type: LableItem['type']): LableItem[] => {
    return this.lables.filter(item => item.type === type);
  };
  
  /**
   * 根据文本搜索标签
   * @param keyword 搜索关键词
   * @returns 搜索结果列表
   */
  searchLables = (keyword: string): LableItem[] => {
    const lowerKeyword = keyword.toLowerCase();
    return this.lables.filter(item => 
      item.text.toLowerCase().includes(lowerKeyword)
    );
  };
  
  /**
   * 异步获取标签列表
   * 模拟从API获取数据
   * @param params 查询参数
   */
  *fetchLables(params?: {
    page?: number;
    pageSize?: number;
    type?: LableItem['type'];
  }) {
    this.loading = true;
    this.error = null;
    
    try {
      // 模拟异步请求延迟
      yield new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟API返回的数据
      const mockLables: LableItem[] = [
        {
          id: '1',
          text: '管理员',
          type: 'primary',
          size: 'medium',
          closable: false,
          disabled: false,
          createdAt: Date.now() - 86400000,
          extra: { roleId: 1 },
        },
        {
          id: '2',
          text: '普通用户',
          type: 'default',
          size: 'medium',
          closable: false,
          disabled: false,
          createdAt: Date.now() - 172800000,
          extra: { roleId: 2 },
        },
        {
          id: '3',
          text: 'VIP会员',
          type: 'success',
          size: 'medium',
          closable: false,
          disabled: false,
          createdAt: Date.now() - 259200000,
          extra: { roleId: 3 },
        },
        {
          id: '4',
          text: '即将过期',
          type: 'warning',
          size: 'medium',
          closable: true,
          disabled: false,
          createdAt: Date.now() - 345600000,
          extra: { expiredDays: 3 },
        },
        {
          id: '5',
          text: '已禁用',
          type: 'error',
          size: 'medium',
          closable: true,
          disabled: true,
          createdAt: Date.now() - 432000000,
          extra: { disabledAt: Date.now() - 86400000 },
        },
      ];
      
      // 应用筛选条件
      let filteredLables = [...mockLables];
      if (params?.type) {
        filteredLables = filteredLables.filter(item => item.type === params.type);
      }
      
      // 应用分页
      const page = params?.page || 1;
      const pageSize = params?.pageSize || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedLables = filteredLables.slice(startIndex, endIndex);
      
      // 更新状态
      // 清空现有数组并添加新元素
      this.lables.length = 0;
      paginatedLables.forEach(lable => this.lables.push(lable));
      this.totalCount = filteredLables.length;
      
      return { lables: paginatedLables, total: filteredLables.length };
    } catch (error) {
      this.error = error instanceof Error ? error.message : '获取标签列表失败';
      throw error;
    } finally {
      this.loading = false;
    }
  };
}

// 导出单例Store
export default new LableStore();